package org.blogwu.learn.multithread.chapter3.demo2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) {
        TImeLock r1 = new TImeLock("r1");
        TImeLock r2 = new TImeLock("r2");
        r1.start();
        r2.start();
    }
}

class TImeLock extends Thread {
    static ReentrantLock reentrantLock1 = new ReentrantLock();

    public TImeLock(String name) {
        super(name);
    }

    @Override
    public void run() {
        try {
            // .tryLock(5, TimeUnit.SECONDS)  设置获取锁的等待时间,  单位为秒,5秒钟
            if (reentrantLock1.tryLock(5, TimeUnit.SECONDS)) {
                Thread.sleep(6000);
            } else {
                System.out.println("获取锁失败");
            }
            System.out.println(Thread.currentThread().getName() + " 执行完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + " " + reentrantLock1.isHeldByCurrentThread());
            if (reentrantLock1.isHeldByCurrentThread()) {
                System.out.println(Thread.currentThread().getName() + " 释放锁");
                reentrantLock1.unlock();
            }
        }
    }
}

